package com.admin_system.mapper;

import com.admin_system.entity.Notice;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 公告Mapper接口
 * 处理公告相关的数据库操作
 */
@Mapper
public interface NoticeMapper {
    
    /**
     * 获取所有公告列表，按发布时间倒序排列
     * @return 公告列表
     */
    @Select("SELECT n.id, n.title, n.content, n.type, n.publish_time, " +
            "CASE WHEN u.full_name IS NOT NULL AND u.full_name != '' THEN u.full_name " +
            "ELSE n.publish_user END as publish_user " +
            "FROM notices n " +
            "LEFT JOIN users u ON n.publish_user = u.username " +
            "ORDER BY n.publish_time DESC")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "title", column = "title"),
        @Result(property = "content", column = "content"),
        @Result(property = "type", column = "type"),
        @Result(property = "publishTime", column = "publish_time"),
        @Result(property = "publishUser", column = "publish_user")
    })
    List<Notice> findAll();
    
    /**
     * 根据ID获取公告详情
     * @param id 公告ID
     * @return 公告对象
     */
    @Select("SELECT n.id, n.title, n.content, n.type, n.publish_time, " +
            "CASE WHEN u.full_name IS NOT NULL AND u.full_name != '' THEN u.full_name " +
            "ELSE n.publish_user END as publish_user " +
            "FROM notices n " +
            "LEFT JOIN users u ON n.publish_user = u.username " +
            "WHERE n.id = #{id}")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "title", column = "title"),
        @Result(property = "content", column = "content"),
        @Result(property = "type", column = "type"),
        @Result(property = "publishTime", column = "publish_time"),
        @Result(property = "publishUser", column = "publish_user")
    })
    Notice findById(Long id);
    
    /**
     * 新增公告
     * @param notice 公告对象
     * @return 受影响的行数
     */
    @Insert("INSERT INTO notices(title, content, type, publish_time, publish_user) " +
            "VALUES(#{title}, #{content}, #{type}, #{publishTime}, #{publishUser})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Notice notice);
    
    /**
     * 更新公告
     * @param notice 公告对象
     * @return 受影响的行数
     */
    @Update("UPDATE notices SET title = #{title}, content = #{content}, " +
            "type = #{type} WHERE id = #{id}")
    int update(Notice notice);
    
    /**
     * 删除公告
     * @param id 公告ID
     * @return 受影响的行数
     */
    @Delete("DELETE FROM notices WHERE id = #{id}")
    int delete(Long id);
    
    /**
     * 统计公告总数
     * @return 公告总数
     */
    @Select("SELECT COUNT(*) FROM notices")
    int countTotal();
} 